package com.yfh.sharding.aop.aspect;


import com.yfh.sharding.aop.annotation.ShardingCut;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.hint.HintManager;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;


/**
 * @author zhangQiang
 * @version 1.0
 * @date 2021-01-04 11:54
 */
@Aspect
@Configuration
@Slf4j
public class ShardingCutAspect {

    /*自定义织入点*/
    @Pointcut("@annotation(com.yfh.sharding.aop.annotation.ShardingCut)")
    public void shardingCut() {

    }

    HintManager hintManager = HintManager.getInstance();

    /**
     * 切换数据源
     * @param point
     */
    @Before("shardingCut()")
    public void doBefore(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        ShardingCut cut = method.getAnnotation(ShardingCut.class);
        String dataSource = cut.dataSource();
        hintManager.setDatabaseShardingValue(dataSource);
        log.info("当前选中的数据源为：{}", dataSource);
    }

    /**
     * 切换数据源
     * @param point
     */
    @After("shardingCut()")
    public void doAfter(JoinPoint point) {
        hintManager.close();
        log.info("方法执行完毕，已关闭当前数据源");

    }
}
